package com.zmn.oms.business.impl.mastercontact;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.consts.GlobalConsts;
import com.zmn.oms.business.interfaces.mastercontact.OrderMasterContactBService;
import com.zmn.oms.business.interfaces.messageV1.common.MessageSendBaseService;
import com.zmn.oms.common.annotation.ZsNormalOrderWorkLog;
import com.zmn.oms.common.constant.MessageConsts;
import com.zmn.oms.common.constant.OrderLogConsts;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.model.dto.work.masterwork.ContactUserDTO;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.masterworking.MasterWorkingService;
import com.zmn.track.common.constant.TrackConfigConsts;
import com.zmn.track.common.constant.TrackConsts;
import com.zmn.track.dubbo.dto.CompleteTrackDIO;
import com.zmn.track.dubbo.dto.TrackWorkDIO;
import com.zmn.track.dubbo.dto.TrackWorkDRO;
import com.zmn.track.dubbo.dto.TrackWorkQuery;
import com.zmn.track.dubbo.interfaces.trackwork.TrackWorkListRemoteService;
import com.zmn.track.dubbo.interfaces.trackwork.TrackWorkModifyRemoteService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 类描述：工程师电话联系
 *
 * @author ligang
 * @date 2021/11/22 10:14
 */
@Service
@Slf4j
public class OrderMasterContactBServiceImpl implements OrderMasterContactBService {

    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private MessageSendBaseService messageSendBaseService;
    @Autowired
    MasterWorkingService masterWorkingService;

    @Reference(version = com.zmn.track.dubbo.consts.DubboConsts.INTERFACE_VERSION, check = false)
    private TrackWorkModifyRemoteService trackWorkModifyRemoteService;
    @Reference(version = com.zmn.track.dubbo.consts.DubboConsts.INTERFACE_VERSION, check = false)
    private TrackWorkListRemoteService trackWorkListRemoteService;

    /**
     * 电话解决
     *
     * @param contactUserDTO
     */
    @ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_TELEPHONE_SOLUTION)
    @Transactional
    public void masterTelephoneSolution(ContactUserDTO contactUserDTO) throws OmsBaseException {
        // 订单详情
        OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(contactUserDTO.getOrderId());
        // 给用户发短信
        Map smsMap = Maps.newHashMap();
        log.info("师傅电话解决: orderId={} 发送短信通知用户 入参{}", contactUserDTO.getOrderId(), smsMap);
        boolean sendTextMessageFlag = messageSendBaseService.sendTextMessage(MessageConsts.ZMN_MSG_RULEID_TELEPHONE_SOLUTION,
                orderDetail.getTelephone(), smsMap);
        if (!sendTextMessageFlag) {
            throw new OmsBaseException("发送短信失败");
        }
        // 返修已修好跟单
        this.addReworkHasBeenRepairedTrack(contactUserDTO);
    }

    /**
     * 师傅再次联系
     *
     * @param contactUserDTO
     * @throws OmsBaseException
     */
    @Override
    @ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_CONTACT_USER_AGAIN)
    public void masterContactUserAgain(ContactUserDTO contactUserDTO) {
        log.info("师傅再次联系: 入参{}", JSON.toJSONString(contactUserDTO));
        TrackWorkQuery query = new TrackWorkQuery();
        query.setOrderId(contactUserDTO.getOrderId());
        query.setWorkId(contactUserDTO.getWorkId());
        query.setTrackContentIdList(Lists.newArrayList(TrackConfigConsts.TRACK_CONTENT_ID_ENGINEER_NEEDS_TO_CONTACT_AGAIN,TrackConfigConsts.TRACK_CONTENT_ID_CONTACT_TIMEOUT_C));
        query.setNotStatus(TrackConsts.TRACK_STATUS_FINISHED);
        ResponseDTO<List<TrackWorkDRO>> listResponseDTO = trackWorkListRemoteService.listTrackByQuery(query);
        if (!listResponseDTO.isSuccess() || CollectionUtil.isNullOrEmpty(listResponseDTO.getData())) {
            return;
        }
        // 完结跟单
        listResponseDTO.getData().forEach(trackWorkDRO -> {
            CompleteTrackDIO completeTrackDIO = BeanMapper.map(trackWorkDRO, CompleteTrackDIO.class);
            completeTrackDIO.setOperator(GlobalConsts.getOperatorTypeName(GlobalConsts.OPERATE_USER_TYPE_SYSTEM));
            completeTrackDIO.setOperatorId((long) GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
            completeTrackDIO.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
            ResponseDTO responseDTO = trackWorkModifyRemoteService.completeTrack(completeTrackDIO);
            if (!responseDTO.isSuccess()) {
                log.info("师傅再次联系 完结跟单-处理失败，入参：{}，出参：{}", JSON.toJSONString(contactUserDTO), JSON.toJSONString(responseDTO));
            }
        });
    }

    /**
     * 发起返修已修好
     *
     * @param contactUserDTO
     */
    void addReworkHasBeenRepairedTrack(ContactUserDTO contactUserDTO) {
        TrackWorkDIO trackDIO = new TrackWorkDIO();
        trackDIO.setOrderId(contactUserDTO.getOrderId());
        trackDIO.setWorkId(contactUserDTO.getWorkId());
        trackDIO.setTrackContentId(TrackConfigConsts.TRACK_CONTENT_ID_REWORK);
        trackDIO.setReasonId(TrackConfigConsts.TRACK_REASON_ID_TELEPHONE_SOLUTION);
        trackDIO.setOperator(GlobalConsts.getOperatorTypeName(GlobalConsts.OPERATE_USER_TYPE_SYSTEM));
        trackDIO.setOperatorId((long) GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
        trackDIO.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
        trackDIO.setOperatorLogRemark(contactUserDTO.getOperatorLogRemark());
        ResponseDTO responseDTO = trackWorkModifyRemoteService.addTrack(trackDIO);
        if (!responseDTO.isSuccess()) {
            log.info("返修已修好跟单 发起跟单-处理失败 入参：{}，出参：{}", JSON.toJSONString(trackDIO), JSON.toJSONString(responseDTO));
        }
    }
}